//需要24点重置的数据
const PlayerReset = require('./playerReset');
const redisBase = require('../../common/RedisBase');
const log = require("../../utils/log");
const schedule = require('node-schedule');

class HallReset {
    static getInstance(){
        if(!HallReset.instance){
            HallReset.instance = new HallReset();
            return HallReset.instance;
        }else{
            return HallReset.instance;
        }
    }

    constructor() {
        log.info('=======HallReset====constructor=============')

        //写在这里无效，写到了
        // ：在每天的23:resetDate 重置部分数据
        // this.scheduleFunction('46 11 * * *');
    }

    scheduleFunction(time) {
        log.info('=======HallReset====scheduleFunction=============',time)
        // 使用node-schedule库创建定时任务
        const job = schedule.scheduleJob(time, () => {
            // 在指定时间执行函数
            this.resetDate();
        });
    }

    //定时执行
    async resetDate(){
        log.info('========HallReset==resetDate 重置每日挑战数据===========');
        let list = await redisBase.getResetList();
        for (let i = 0; i < list.length ; i++) {
            let rd = JSON.parse(list[i]);
            rd.freeCjCur = 0; //看视频免费抽奖
            //更新挑战列表数据
            await redisBase.updateResetList(i,JSON.stringify(rd));
        }
    }

    async addResetData(uid){
        let isHava = false;
        let list = await redisBase.getResetList();
        if(list){
            for (let i = 0; i < list.length; i++) {
                let cfg = JSON.parse(list[i]);
                if(cfg.uid === uid){
                    isHava = true;
                    break;
                }
            }
        }

        if(!isHava){
            let reset = new PlayerReset(uid);
            await redisBase.addResetToList(reset);
        }
    }

    //取重置数据
    async getResetData(uid){
        let res = null;
        let list = await redisBase.getResetList();
        for (let i = 0; i < list.length; i++) {
            let cfg = JSON.parse(list[i]);
            if(cfg.uid === uid){
                res = cfg;
                break;
            }
        }
        return res;
    }

    //更新重置数据
    async updateResetData(uid, d){
        let list = await redisBase.getResetList();
        for (let i = 0; i < list.length; i++) {
            let cfg = JSON.parse(list[i]);
            if(cfg.uid === uid){
                await redisBase.updateResetList(i, JSON.stringify(d));
                break;
            }
        }
    }
    
}

module.exports = HallReset.getInstance();